package com.uicole.push.server.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.uicole.push.server.dao.AppInfoDao;
import com.uicole.push.server.dao.DeviceInfoDao;
import com.uicole.push.server.model.AppInfo;
import com.uicole.push.server.model.DeviceInfo;
import com.uicole.push.server.model.PushMsg;
import com.uicole.push.server.model.Result;
import com.uicole.push.server.service.PushMsgService;

@Service("pushMsgService")
public class PushMsgServiceImpl extends GenericManagerImpl<PushMsg, Long> implements PushMsgService {
	@Autowired
	private DeviceInfoDao deviceInfoDao;
	@Autowired
	private AppInfoDao appInfoDao;
	@Transactional
	public Result trySave(PushMsg pushMsg ,String ip){
		String appId = pushMsg.getAppId();
		List<AppInfo> appInfos = appInfoDao.find("from AppInfo appInfo where appInfo.appId=?", appId);
		if(appInfos==null||appInfos.size()==0){
			return new Result(1, new HashMap(), "appId不存在\t"+ip);
		}else if(appInfos.size()>1){
			return new Result(2, new HashMap(), "推送appId存重复注册\t"+ip);
		}else{
			AppInfo AppInfo=appInfos.get(0);
			String bindIp = AppInfo.getBindIp();
			if(bindIp==null||!bindIp.trim().equals(ip)){
				return new Result(3, new HashMap(), "非法的ip地址:"+ip+",期待ip;"+bindIp);
			}else{
				int type = pushMsg.getType();
				List<DeviceInfo> deviceInfos = deviceInfoDao.find("from DeviceInfo deviceInfo where deviceInfo.appId=?", appId);
				String toUser = pushMsg.getToUser();
				String[] toUsers = toUser.split(",");
				if(type==1||type==2){
					List<String> errors=new ArrayList<String>();
					for(String t:toUsers){
						boolean in=false;
						for(DeviceInfo deviceInfo:deviceInfos){
							String deviceId = type==1?deviceInfo.getDeviceId():deviceInfo.getAlias();
							if(deviceId.trim().equals(t)){
								in=true;
								break;
							}
						}
						if(!in){
							errors.add(t);
						}
					}
					if(errors.size()>0){
						return new Result(type==1?4:2, errors, "非法的"+(type==1?"设备编号":"别名"));
					}else{
						return saveMsg(pushMsg);
					}
				}else{
					return saveMsg(pushMsg);
				}
			}
		}
	}
	private Result saveMsg(PushMsg pushMsg) {
		pushMsg.setCreateTime(new Date());
		pushMsg.setPushId(UUID.randomUUID().toString().replace("-", "")+(System.currentTimeMillis()+"").substring(7));
		save(pushMsg);
		return new Result(0, new HashMap(), "推送成功");
	}
}
